package com.wandian.ui.controls
{
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.FullScreenEvent;
	import flash.events.MouseEvent;
	
	import com.wandian.ui.events.ButtonEvent;
	import com.wandian.ui.skins.Skin;




	public class Button extends UIComponent
	{

		private var _phase:String="up";
		protected var skin:Skin;

		private var clickHandler:Function
		public function Button(w:int=100, h:int=32)
		{
			super(w, h);
			mouseChildren=false;
			this.tabEnabled=true;
			this.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler)
			this.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler)
			this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler)
			this.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler)
			this.addEventListener(MouseEvent.CLICK, mouseClickHandler)

		}

		private function mouseClickHandler(e:MouseEvent):void{
			if(clickHandler!=null){
			clickHandler();
			}
		}
		public function getClickHandler():Function{
			return clickHandler;
		}
		
		public function setClickHandler(v:Function):void{
			clickHandler=v
		}
		
		override protected function createChildren():void
		{
			var skinClass:Class=this.getStyle("skin") as Class
			skin=new skinClass() as Skin
			skin.styleClient=this
			this.addChild(skin);
		}

		override protected function updateDisplay(w:int, h:int):void
		{
			updatePhaseDisplay(w, h)
		}

		protected function updatePhaseDisplay(w:int, h:int):void
		{
			skin.updateDisplay(w, h, enabled ? _phase : "disabled")
		}

		private function mouseOverHandler(e:MouseEvent):void
		{
			//正常
			if (_phase == "up")
			{
				if (e.buttonDown)
				{
					return;
				}
				phase="over"
			}
			else if (_phase == "over")
			{
				phase="down"
			}

		}

		private function mouseOutHandler(e:MouseEvent):void
		{
			if (_phase == "over")
			{
				phase="up"
			}
			else if (_phase == "down")
			{
				phase="over"
			}
		}

		private function mouseDownHandler(e:MouseEvent):void
		{
			manager.getStage().addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler)
			phase="down";
		}

		private function mouseUpHandler(e:MouseEvent):void
		{
			if (_phase == "down" || _phase == "over")
			{
				manager.getStage().removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
				phase=_phase == "down" ? "over" : "up";

				this.dispatchEvent(new ButtonEvent(ButtonEvent.Release))
			}
			else if (_phase == "up")
			{
				phase="over";
			}
		}

		public function get phase():String
		{
			return _phase;
		}

		public function set phase(v:String):void
		{
			if (v == _phase)
			{
				return;
			}
			_phase=v;
			updatePhaseDisplay(width, height);
		}

		override public function set enabled(v:Boolean):void
		{
			super.enabled=this.mouseEnabled=v;
		}
	}
}
